import { memo, useCallback, useEffect, useState } from "react";
import { Position, useReactFlow, Node } from "@xyflow/react";
import { Card, Modal, Select } from "antd";
import useSelectBorder from "@/store/useSceneData";
import CustomHandle from "@/flow/CustomHandle";
import Subtitle from "@/components/Subtitle";
import NodeOperation from "@/components/NodeOperation";
import LexicalEdit from "@/components/LexicalEdit";

/**
 * 提示词模版
 * @param param0
 * @returns
 */
function OutputNode({ id, data }: Node) {
  const { select, setSelectId, debug } = useSelectBorder()
  const { setNodes, setCenter } = useReactFlow();
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 回复
  const [reply, setReply] = useState('');
  const [selectedOption, setSelectedOption] = useState(data.type || 'text');

  const onChangeText = useCallback((value) => {
    setReply(value);
  }, []);

  const onChangeType = useCallback((value: string) => {
    setSelectedOption(value);
    setNodes((nodes) => {
      const node = nodes.find(node => node.id == id)
      node.data.type = value
      return [...nodes];
    })
  }, []);

  useEffect(() => {
    if (select[id] && debug) {
      setNodes((nodes) => {
        const node = nodes.find(node => node.id == id)
        setCenter(node.position.x + 200, node.position.y, { zoom: 1, duration: 500 })
        return [...nodes];
      })
    }
  }, [select[id]])

  useEffect(() => {
    if (isModalOpen) {
      setReply(data.replyAtom as string || '');
    }
  }, [isModalOpen])

  return (
    <NodeOperation nodeId={id} onClick={() => setIsModalOpen(true)}>
      <Card
        title={<div className='flex'>
          <Subtitle imgUrl='img/output.png' title={data.title as string || '回复'} id={id} />
        </div>}
        style={{
          outline: select[id] ? "2px solid #145FF0" : "none",
          width: 310,
        }}
        onClick={() => setSelectId(id)}
        tabIndex={0}
      >
        <div className="flex flex-col">
          <Select
            showSearch
            placeholder="选择类型"
            optionFilterProp="label"
            style={{ width: 254 }}
            onChange={value => onChangeType(value as string)}
            value={selectedOption}
            className="nodrag"
            options={[
              {
                value: 'text',
                label: '文本输出',
              },
              {
                value: 'audio',
                label: '语音输出',
              }
            ]}
          />
        </div>
        <CustomHandle count={10} type="target" position={Position.Left} id="output" style={{ top: 74 }} />

        <Modal
          title={<span>{data.title as string || '回复'}</span>}
          open={isModalOpen}
          footer={false}
          destroyOnClose={true}
          onCancel={() => {
            setNodes((nodes) => {
              const node = nodes.find(node => node.id == id)
              if (reply) {
                const jsonData = JSON.parse(reply)
                node.data.replyAtom = reply
                const data = jsonData["root"].children[0].children.map(item => item?.content?.value || item?.text)
                node.data.reply = data.join('')
              }
              return [...nodes];
            })
            setIsModalOpen(false)
          }}>
          <LexicalEdit onChange={onChangeText} value={reply} />
        </Modal>
      </Card>
    </NodeOperation>
  );
}

export default memo(OutputNode);
